var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var pool = require('./conf/db.js')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var sql = require('./conf/sql')

var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

app.post('/v1/emps', (req, res, next) => {

  // pool.queryAll(sql.insertUser, req.body)
  pool.query(sql.insertUser, [req.body], (err, result) => {
    if (err) {
      next(err)
      return;
    }
    res.json({
      code: 200,
      msg: 'employee sucess',
      data: req.body
    })
  })



})

app.get('/v1/emps/:id', (req, res, next) => {
  pool.query(sql.queryUser, [req.params.id], (err, result) => {
    if (err) {
      next(err)
      return;
    }
    res.json({
      code: 200,
      msg: '查询成功',
      data: result
    })
    console.log(result.affectedRows);
  })
})

app.delete('/v1/emps/', (req, res, next) => {
  pool.query(sql.deleteUser, [req.query.id], (err, result) => {
    // console.log(req.query);
    if (err) {
      next(err)
      return;
    }
    if (result.affectedRows == 0) {
      res.json({
        code: 201,
        msg: '删除失败',
      })
    } else {
      res.json({
        code: 200,
        msg: '删除成功',
      })
    }
    // console.log(result);

  })
})

app.put('/v1/emps/', (req, res, next) => {

  pool.query(sql.updateUser, [req.body, req.body.id], (err, result) => {
    if (err) {
      next(err)
      return;
    }
    console.log(result.affectedRows);
    if (result.affectedRows == 0) {
      res.json({
        code: 201,
        msg: '修改失败',
      })
    } else {
      res.json({
        code: 200,
        msg: '修改成功',
      })
    }

  })
})

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use('/', function (err, req, res, next) {
  // set locals, only providing error in development
  // res.locals.message = err.message;
  // res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  console.log(err);
  res.status(err.status || 500);
  res.json({
    code: 500,
    msg: 'error'
  });
});

module.exports = app;
